import { useRef } from 'react';
import { Button, Table, message, Tooltip, Modal, Upload } from 'antd';
import { history } from 'umi';
import SearchAndTable from '@/components/SearchAndTable';
import { ProFormText } from '@ant-design/pro-form';
import { ProColumnType } from '@ant-design/pro-table';
import { fetchEnrollBookList, deleteBook } from '@/service/enrollBook';
import { PageConfigParams } from '@/components/SearchAndTable/interface';
import { RequestParams, EnrollBookState } from './interface';
import DefaultCollapseHeader from '@/components/SearchAndTable/components/DefaultCollapseHeader';
import styles from './index.scss';
import { EditTwoTone, DeleteTwoTone, EyeTwoTone } from '@ant-design/icons';
import { UploadProps } from 'antd/lib/upload';
import { uploadFile } from '@/service/personnelEntry';
const columns: ProColumnType<EnrollBookState>[] = [
    {
        title: 'RFID编号',
        key: 'rfid',
        dataIndex: 'rfid',
    },
    {
        title: '订单编号',
        key: 'id',
        dataIndex: 'id',
    },
    {
        title: 'ISBN编号',
        key: 'isbn',
        dataIndex: 'isbn',
    },
    {
        title: '书名',
        key: 'book_name',
        dataIndex: 'book_name',
    },
    {
        title: '作者',
        key: 'author',
        dataIndex: 'author',
    },
    {
        title: '类别',
        key: 'cate_name',
        dataIndex: 'cate_name',
        // valueType: 'select',
    },
    {
        title: '出版社',
        key: 'publishing_house',
        dataIndex: 'publishing_house',
    },
    {
        title: '出版时间',
        key: 'publish_date',
        dataIndex: 'publish_date',
    },
    {
        title: '条形码',
        key: 'img_url',
        dataIndex: 'img_url',
        hideInSearch: true,
    },
    {
        title: '操作',
        hideInSearch: true,
        render: (text, record, _, action) => [
            <Tooltip title="查看">
                <EyeTwoTone
                    style={{ padding: '0 5px' }}
                    onClick={(e) => {
                        e.stopPropagation();
                        history.push(`/enrollBook/details/${record.id}`);
                    }}
                />
            </Tooltip>,
            <Tooltip title="编辑">
                <EditTwoTone
                    style={{ padding: '0 5px' }}
                    onClick={(e) => {
                        e.stopPropagation();
                        history.push(`/enrollBook/editBook/${record.id}`);
                    }}
                />
            </Tooltip>,
            <Tooltip title="删除">
                <DeleteTwoTone
                    style={{ padding: '0 5px' }}
                    onClick={(e) => {
                        e.stopPropagation();
                        detele(record.id);
                    }}
                />
            </Tooltip>,
        ],
    },
];
const detele = (bookid: string) => {
    Modal.confirm({
        icon: '',
        title: '确认删除',
        content: `您确定要删除当前记录么？`,
        okText: '确认',
        cancelText: '取消',
        maskClosable: true,
        onOk: async () => {
            const response = await deleteBook({ book_id: bookid });
            if (response?.code === 200) {
                message.success('删除成功');
                history.push('/enrollBook');
            } else {
                message.success('删除失败');
            }
        },
        onCancel() {},
    });
};
const toEnrollBookAdd = () => {
    history.push('/enrollBook/addBook');
};
// const toEnrollBookDetails = (record: EnrollBookState) => {
//     history.push(`/enrollBook/details/${record.id}`);
// };

export default function EnrollBook() {
    const selectedRowsRef = useRef<EnrollBookState[]>([]);
    const dataSourceRequest = async ({
        pageSize = 10,
        current = 1,
        ...params
    }: PageConfigParams & RequestParams) => {
        console.log({
            pageSize,
            current,
            ...params,
        });
        const response = await fetchEnrollBookList({
            pageSize,
            current,
            ...params,
        });

        if (response.code !== 200) {
            return {
                total: 0,
                data: [],
            };
        }
        return response.data;
    };

    const toEnrollBookMultipleModify = () => {
        let arr = selectedRowsRef.current.map((i) => i.id);
        history.push(`/enrollBook/editBook/${arr}`);
    };
    const toEnrollBookMultipleAddHandler = () => {};

    const toEnrollBookMultipleModifyHandler = () => {
        if (!selectedRowsRef.current.length) {
            message.info('请选择具体列');
            return;
        }
        toEnrollBookMultipleModify();
    };
    const customRequest: UploadProps['customRequest'] = async (options) => {
        const formdata = new FormData();
        formdata.append('field', 'books');
        formdata.append('books', options.file);
        const res = await uploadFile(formdata);
        if (res.code !== 200) {
            message.error(res.msg);
            return;
        }
        message.error('上传成功');
        history.push('/enrollBook/addBook');
        options.onSuccess?.(res.data.url);
    };
    const customRequestsync: UploadProps['customRequest'] = async ({
        file,
        onError,
        onSuccess,
    }) => {
        const formdata = new FormData();
        formdata.append('field', 'ebook');
        formdata.append('ebook', file);
        const res = await uploadFile(formdata);
        if (res.code !== 200) {
            message.error(res.msg);
            return;
        }
        message.error('上传成功');
        onSuccess?.(res.data.url);
    };
    return (
        <>
            <SearchAndTable<EnrollBookState, RequestParams>
                columns={columns}
                request={dataSourceRequest}
                renderCollapseHeader={(params) => {
                    return (
                        <DefaultCollapseHeader collapseHeader={params}>
                            <ProFormText
                                disabled={params.collapse}
                                name="rfid"
                                placeholder="请输入RFID标识码"
                            />
                        </DefaultCollapseHeader>
                    );
                }}
                renderController={() => {
                    return (
                        <div
                            className={styles.controller}
                            style={{ display: 'flex' }}
                        >
                            <Button type="primary" onClick={toEnrollBookAdd}>
                                新增书籍
                            </Button>
                            <Upload
                                customRequest={customRequest}
                                accept={
                                    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                                }
                                showUploadList={false}
                            >
                                <Button>批量导入书籍</Button>
                            </Upload>
                            {/* <Button onClick={toEnrollBookMultipleModifyHandler}>
                                批量编辑
                            </Button> */}
                            <Upload
                                showUploadList={false}
                                customRequest={customRequestsync}
                                multiple
                                method="post"
                            >
                                <Button>一键同步</Button>
                            </Upload>
                        </div>
                    );
                }}
                tableProps={{
                    tableAlertRender: false,
                    rowSelection: {
                        selections: [
                            Table.SELECTION_ALL,
                            Table.SELECTION_INVERT,
                        ],
                        onChange: (rows, state) => {
                            selectedRowsRef.current = state;
                        },
                    },
                    rowKey: 'id',
                    // onRow: (record) => {
                    //     return {
                    //         onClick: (event) => {
                    //             event.stopPropagation();
                    //             toEnrollBookDetails(record);
                    //         }, // 点击行
                    //     };
                    // },
                    scroll: {
                        x: 1000,
                        y: 500,
                        scrollToFirstRowOnChange: true,
                    },
                }}
            />
        </>
    );
}
